package fragment;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigchun.seeland.GoodsInfomationActivity;
import com.bigchun.seeland.LoginActivity;
import com.bigchun.seeland.R;
import com.bigchun.seeland.SearchActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.GoodsFragmentAdapter;
import adapter.GoodsRecyclerViewAdapter;
import adapter.ShaixuanAdapter;
import bean.ContentDataBean;
import bean.GoodsBean;
import bean.GoodsShaixuanBean;
import bean.ShaixuanallBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.PullLoadMoreRecyclerView;
import myview.XCFlowLayout;
import util.DensityUtil;
import util.MyLog;
import util.OrderEventMessage;
import util.RequestManager;
import util.utils;

public class GoodsFragment extends Fragment implements View.OnClickListener {

    private View view;
    private Context mcontext;
    private LinearLayout ll_reback;
    private LinearLayout ll_nodata;
    private LinearLayout ll_shaixuan;
    private TextView et_search_content;
    private LinearLayout ll_caizhi;
    private TextView tv_caizhi;
    private ImageView img_caizhi;
    private LinearLayout ll_color;
    private TextView tv_color;
    private ImageView img_color;
    private LinearLayout ll_function;
    private TextView tv_function;
    private ImageView img_function;
    private LinearLayout ll_area;
    private TextView tv_area;
    private ImageView img_area;
    private TextView tv_shaixuan;
    private ImageView img_shaixuan;
    private LinearLayout ll_screen;
    private LinearLayout ll_search;
    private GridView gridview;
    private int heightPixels;
    private PopupWindow mPopupWindow;
    private ShaixuanAdapter sadapter;
    private MyApp myapp;
    private String token;
    private List<ShaixuanallBean.DataBean> temshaixuanallList = new ArrayList<>();//筛选多条件临时数据
    private LayoutInflater mInflater;
    private List<String> clickids = new ArrayList<>();
    List<XCFlowLayout> viewssss = new ArrayList<>();
    private int page = 1;
    private int size = 20;
    private List<GoodsBean.DataBean> temgoodsList = new ArrayList<>();
    private List<GoodsBean.DataBean> goodsList = new ArrayList<>();
    private GoodsFragmentAdapter goodsadapter;
    private List<GoodsShaixuanBean.DataBean> temSXTabList = new ArrayList<>();
    private PullLoadMoreRecyclerView goodsRecycleView;
    private GoodsRecyclerViewAdapter adapter;
    private int width;
    private View bottomView;
    private LinearLayout loadLlay;
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private CustomProgressDialog customProgressDialog;
    private RelativeLayout rl_top;
    private ContentDataBean.DataBean textContent;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MyLog.e("Activity:", this.getClass().getName().toString());
        view = inflater.inflate(R.layout.fragment_goods, container, false);
        mcontext = getActivity();
        myapp = (MyApp) mcontext.getApplicationContext();


        sharedPreferences = mcontext.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        textData = sharedPreferences.getString("textData", "");
        mInflater = LayoutInflater.from(mcontext);

        customProgressDialog = new CustomProgressDialog(mcontext, "", R.style.CommProgressDialog);
        customProgressDialog.show();
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
        EventBus.getDefault().register(this);
        getScreenDen();
        initView();
        initTopView();
        initData();
        initLin();
        getTitleData();
        getShaixuanResultData("");
        getShaixuanData();

        return view;

    }
    @Subscribe
    public void onEventMainThread(OrderEventMessage event) {
        String message = event.getMessage();
        MyLog.e("message--new--order", message);
        if ("刷新数据".equals(message)) {
            page = 1;
            getShaixuanResultData("");
        }

    }
    private void initData() {

        goodsadapter = new GoodsFragmentAdapter(mcontext, temgoodsList);
        gridview.setAdapter(goodsadapter);
    }


    private void initView() {
        rl_top = view.findViewById(R.id.rl_top);
        ll_reback = view.findViewById(R.id.ll_reback);
        ll_nodata = view.findViewById(R.id.ll_nodata);
        ll_shaixuan = view.findViewById(R.id.ll_shaixuan);
        et_search_content = view.findViewById(R.id.et_search_content);
        ll_caizhi = view.findViewById(R.id.ll_caizhi);
        tv_caizhi = view.findViewById(R.id.tv_caizhi);
        img_caizhi = view.findViewById(R.id.img_caizhi);
        ll_color = view.findViewById(R.id.ll_color);
        tv_color = view.findViewById(R.id.tv_color);
        img_color = view.findViewById(R.id.img_color);
        ll_function = view.findViewById(R.id.ll_function);
        tv_function = view.findViewById(R.id.tv_function);
        img_function = view.findViewById(R.id.img_function);
        tv_shaixuan = view.findViewById(R.id.tv_shaixuan);
        img_shaixuan = view.findViewById(R.id.img_shaixuan);
        ll_area = view.findViewById(R.id.ll_area);
        tv_area = view.findViewById(R.id.tv_area);
        img_area = view.findViewById(R.id.img_area);
        ll_screen = view.findViewById(R.id.ll_screen);
        ll_search = view.findViewById(R.id.ll_search);
        gridview = view.findViewById(R.id.gridview);
        TextView tv_nodata = view.findViewById(R.id.tv_nodata);
        TextView tv_title = view.findViewById(R.id.tv_title);
        if ("0".equals(apptype)){
            //木头
            ll_area.setVisibility(View.VISIBLE);
        }else if ("1".equals(apptype)){
            //熙然
            ll_area.setVisibility(View.INVISIBLE);
        }

        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        goodsRecycleView = view.findViewById(R.id.rclv_goods);
        adapter = new GoodsRecyclerViewAdapter(temgoodsList, mcontext, myapp,width, textContent);
        setHeader(goodsRecycleView);
        goodsRecycleView.setAdapter(adapter);
        goodsRecycleView.setGridLayout(2);
        goodsRecycleView.setRefreshing(true);
        goodsRecycleView.cancleAnimal();
//        ((SimpleItemAnimator) goodsRecycleView.getItemAnimator()).setSupportsChangeAnimations(false);

        if (textContent != null){
            tv_title.setText(textContent.getGoods());
            tv_nodata.setText(textContent.getNodata());
            tv_shaixuan.setText(textContent.getShuaixuan());
        }


    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {


        //底部加载更多
        bottomView = LayoutInflater.from(mcontext).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {


        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }


    private void initLin() {
        ll_caizhi.setOnClickListener(this);
        ll_color.setOnClickListener(this);
        ll_function.setOnClickListener(this);
        ll_screen.setOnClickListener(this);
        ll_search.setOnClickListener(this);
        ll_area.setOnClickListener(this);
        goodsRecycleView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                /*clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }*/
                //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}
                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                paramJson = paramJson+"}";
                MyLog.e("组合id的json",paramJson+"    JSon格式");

                page = 1;
                if (clickids.size() == 0){
                    paramJson = "";
                }

                getShaixuanResultData(paramJson);
//                goodsRecycleView.setPullLoadMoreCompleted();
            }

            @Override
            public void onLoadMore() {
                /*clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }*/
                //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}

                if (temgoodsList.size() != 0) {

                    customProgressDialog.show();
                    String paramJson = "{";
                    for (int m = 0; m < temshaixuanallList.size(); m++) {
                        //循环遍历每一个大分类的id
                        int id = temshaixuanallList.get(m).getId();
                        StringBuffer sbf = new StringBuffer();
                        sbf.append("\"");
                        sbf.append(id);
                        sbf.append("\":\"");
                        for (int t = 0; t < clickids.size(); t++) {
                            String s = clickids.get(t);
                            String[] split = s.split("=");
                            if (split[1].equals(id + "")) {
                                sbf.append(split[0] + ",");
                            }
                        }
                        boolean isadd = false;
                        if (sbf.toString().contains(",")) {
                            isadd = true;
                        }
                        String substring = sbf.substring(0, sbf.length() - 1);
                        substring = substring + "\",";
                        if (isadd) {
                            paramJson = paramJson + substring;
                        }
                    }
                    paramJson = paramJson.substring(0, paramJson.length() - 1);
                    paramJson = paramJson + "}";
                    MyLog.e("组合id的json", paramJson + "    JSon格式");
                    page++;
                    if (clickids.size() == 0) {
                        paramJson = "";
                    }
                    getShaixuanResultData(paramJson);
                }else{
                goodsRecycleView.setPullLoadMoreCompleted();

                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        //店铺列表点击事件
        adapter.setOnItemClickListener(new GoodsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MyLog.e("条目点击事件",position+"    item");
                int id = goodsList.get(position).getId();
                Intent intent = new Intent(mcontext, GoodsInfomationActivity.class);
                intent.putExtra("goodsid",id+"");
                startActivity(intent);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_caizhi:
                initunitbyWindow("1");
                tv_caizhi.setTextColor(getResources().getColor(R.color.colordorange));
                img_caizhi.setImageResource(R.mipmap.icon_down_orange);
                break;
            case R.id.ll_color:
                initunitbyWindow("2");
                tv_color.setTextColor(getResources().getColor(R.color.colordorange));
                img_color.setImageResource(R.mipmap.icon_down_orange);
                break;
            case R.id.ll_function:
                initunitbyWindow("3");
                tv_function.setTextColor(getResources().getColor(R.color.colordorange));
                img_function.setImageResource(R.mipmap.icon_down_orange);
                break;
            case R.id.ll_area:
                initunitbyWindow("4");
                tv_area.setTextColor(getResources().getColor(R.color.colordorange));
                img_area.setImageResource(R.mipmap.icon_down_orange);
                break;
            case R.id.ll_screen:
                if (utils.isFastDoubleClick()){
                    return;
                }
                if (temshaixuanallList.size() == 0){
                    Toast.makeText(mcontext,textContent.getPlease_retry(),Toast.LENGTH_LONG).show();
                }else{
                    initallbyWindow();
                }

                break;
            case R.id.ll_search:
                Intent intent = new Intent(mcontext, SearchActivity.class);
                intent.putExtra("activityType","");
                intent.putExtra("showroom","");
                startActivity(intent);
                break;
        }
    }

    List<String> tempClickids = new ArrayList<>();
    /**
     * 弹出单个筛选框
     */
    private void initunitbyWindow(final String type) {
        LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
        View popupWindow = layoutInflater.inflate(R.layout.popup_shaixuan, null);
        ListView listview = popupWindow.findViewById(R.id.listview);
        TextView tv_clear = popupWindow.findViewById(R.id.tv_clear);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        View viewById = popupWindow.findViewById(R.id.view_zhezhao);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });

        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_clear.setText(textContent.getResetting());
            tv_sure.setText(textContent.getDefine());
        }

        int checkitem = -1;
        if (sadapter != null){
            listview.setAdapter(sadapter);
            if ("1".equals(type)) {
                sadapter.setData(temSXTabList.get(0).getAttr_list(), checkitem, type,clickids);
            } else if ("2".equals(type)) {
                sadapter.setData(temSXTabList.get(1).getAttr_list(), checkitem, type,clickids);
            } else if ("3".equals(type)) {
                sadapter.setData(temSXTabList.get(2).getAttr_list(), checkitem, type,clickids);
            }else if ("4".equals(type)) {
                sadapter.setData(temSXTabList.get(3).getAttr_list(), checkitem, type,clickids);
            }
        }
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickids.clear();

                String idfu = "";
                if ("1".equals(type)) {
                    if (temSXTabList.get(0).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(0).getAttr_list().get(0).getKind_id()+"";
                    }
                } else if ("2".equals(type)) {
                    if (temSXTabList.get(1).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(1).getAttr_list().get(0).getKind_id()+"";
                    }
                } else if ("3".equals(type)) {
                    if (temSXTabList.get(2).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(2).getAttr_list().get(0).getKind_id()+"";
                    }
                }else if ("4".equals(type)) {
                    if (temSXTabList.get(3).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(3).getAttr_list().get(0).getKind_id()+"";
                    }
                }
                for (int m = 0;m<tempClickids.size();m++){
                    String s = tempClickids.get(m);
                    String[] split = s.split("=");
                    if (!split[1].equals(idfu+"")){
                        clickids.add(tempClickids.get(m));
                    }
                }
                int item = Integer.parseInt(type);
                sadapter.setData(temSXTabList.get(item-1).getAttr_list(), 0, type,clickids);
                tempClickids.clear();
                for (int a = 0;a<clickids.size();a++){
                    tempClickids.add(clickids.get(a));
                }
            }
        });

        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickids.clear();
                customProgressDialog.show();
                String idfu = "";
                if ("1".equals(type)) {
                    if (temSXTabList.get(0).getAttr_list().size() > 0){
                       idfu =  temSXTabList.get(0).getAttr_list().get(0).getKind_id()+"";
                    }
                } else if ("2".equals(type)) {
                    if (temSXTabList.get(1).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(1).getAttr_list().get(0).getKind_id()+"";
                    }
                } else if ("3".equals(type)) {
                    if (temSXTabList.get(2).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(2).getAttr_list().get(0).getKind_id()+"";
                    }
                }else if ("4".equals(type)) {
                    if (temSXTabList.get(3).getAttr_list().size() > 0){
                        idfu =  temSXTabList.get(3).getAttr_list().get(0).getKind_id()+"";
                    }
                }
                for (int m = 0;m<tempClickids.size();m++){
                    String s = tempClickids.get(m);
                    String[] split = s.split("=");
                    if (split[1].equals(idfu+"")){
                        clickids.add(tempClickids.get(m));
                    }
                }

                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                paramJson = paramJson+"}";
                MyLog.e("单分类组合id的json",paramJson+"    JSon格式");


                page = 1;
                if (clickids.size() == 0){
                    paramJson = "";
                }
                boolean isone = false;
                if (!isone){
                    getShaixuanResultData(paramJson);
                    isone = true;
                }
            }
        });
        tempClickids.clear();
        for (int a = 0;a<clickids.size();a++){
            tempClickids.add(clickids.get(a));
        }
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                if ("1".equals(type)) {
                    int idson = temSXTabList.get(0).getAttr_list().get(i).getId();
                    int idfu = temSXTabList.get(0).getAttr_list().get(i).getKind_id();
                    String idzuhe = idson+"="+idfu;
                    int item = -1;
                    for (int p = 0;p<tempClickids.size();p++){
                        if (tempClickids.get(p).equals(idzuhe)){
                            item = p;
                            break;
                        }
                    }
                    if (item != -1){
                        tempClickids.remove(item);
                    }else{
                        tempClickids.add(idzuhe);
                    }
                    sadapter.setData(temSXTabList.get(0).getAttr_list(), i, type,tempClickids);
                } else if ("2".equals(type)) {
                    int idson = temSXTabList.get(1).getAttr_list().get(i).getId();
                    int idfu = temSXTabList.get(1).getAttr_list().get(i).getKind_id();
                    String idzuhe = idson+"="+idfu;
                    int item = -1;
                    for (int p = 0;p<tempClickids.size();p++){
                        if (tempClickids.get(p).equals(idzuhe)){
                            item = p;
                            break;
                        }
                    }
                    if (item != -1){
                        tempClickids.remove(item);
                    }else{
                        tempClickids.add(idzuhe);
                    }
                    sadapter.setData(temSXTabList.get(1).getAttr_list(), i, type,tempClickids);
                } else if ("3".equals(type)) {
                    int idson = temSXTabList.get(2).getAttr_list().get(i).getId();
                    int idfu = temSXTabList.get(2).getAttr_list().get(i).getKind_id();
                    String idzuhe = idson+"="+idfu;
                    int item = -1;
                    for (int p = 0;p<tempClickids.size();p++){
                        if (tempClickids.get(p).equals(idzuhe)){
                            item = p;
                            break;
                        }
                    }
                    if (item != -1){
                        tempClickids.remove(item);
                    }else{
                        tempClickids.add(idzuhe);
                    }
                    sadapter.setData(temSXTabList.get(2).getAttr_list(), i, type,tempClickids);
                } else if ("4".equals(type)) {
                    int idson = temSXTabList.get(3).getAttr_list().get(i).getId();
                    int idfu = temSXTabList.get(3).getAttr_list().get(i).getKind_id();
                    String idzuhe = idson+"="+idfu;
                    int item = -1;
                    for (int p = 0;p<tempClickids.size();p++){
                        if (tempClickids.get(p).equals(idzuhe)){
                            item = p;
                            break;
                        }
                    }
                    if (item != -1){
                        tempClickids.remove(item);
                    }else{
                        tempClickids.add(idzuhe);
                    }
                    sadapter.setData(temSXTabList.get(3).getAttr_list(), i, type,tempClickids);
                }
;
            }
        });


        int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.WRAP_CONTENT);
        mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件

        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(mcontext, 112);
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(ll_shaixuan, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
            mPopupWindow.showAsDropDown(ll_shaixuan);
        }

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                MyLog.e("弹窗消失", "00000000000000");
                tv_caizhi.setTextColor(getResources().getColor(R.color.color333));
                tv_color.setTextColor(getResources().getColor(R.color.color333));
                tv_function.setTextColor(getResources().getColor(R.color.color333));
                tv_area.setTextColor(getResources().getColor(R.color.color333));
                img_caizhi.setImageResource(R.mipmap.icon_down_gray);
                img_color.setImageResource(R.mipmap.icon_down_gray);
                img_function.setImageResource(R.mipmap.icon_down_gray);
                img_area.setImageResource(R.mipmap.icon_down_gray);
            }
        });

    }

    /**
     * 弹出多筛选框
     */
    private void initallbyWindow() {
        viewssss.clear();
        tempClickids.clear();
        for (int m = 0;m<clickids.size();m++){
            tempClickids.add(clickids.get(m));
        }
        clickids.clear();
        LayoutInflater layoutInflater = LayoutInflater.from(mcontext);
        View popupWindow = layoutInflater.inflate(R.layout.popup_allshaixuan, null);
        View viewById = popupWindow.findViewById(R.id.view_zhezhao);
        ImageView img_back_pop = popupWindow.findViewById(R.id.img_back_pop);
        TextView tv_title_name = popupWindow.findViewById(R.id.tv_title_name);
        viewById.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
        img_back_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindow.dismiss();
            }
        });
        TextView tv_clear = popupWindow.findViewById(R.id.tv_clear);
        final LinearLayout ll_content = popupWindow.findViewById(R.id.ll_content);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        ContentDataBean.DataBean textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_clear.setText(textContent.getResetting());
            tv_sure.setText(textContent.getDefine());
        }
        tv_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickids.clear();
                tempClickids.clear();
                for (int m = 0; m < viewssss.size(); m++) {
                    XCFlowLayout viewone = viewssss.get(m);
                    int xccount = viewone.getChildCount();
                    for (int n = 0; n < xccount; n++) {
                        TextView childAt = (TextView) viewone.getChildAt(n);
                        childAt.setBackgroundResource(R.drawable.kong_bg);
                        childAt.setTextColor(getResources().getColor(R.color.color333));
                    }
                }


            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                customProgressDialog.show();
                clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }
      //          {"attr_58": "1,56,23,45","attr_58": "1,56,23,45"}
                String paramJson = "{";
                for (int m = 0;m<temshaixuanallList.size();m++){
                    //循环遍历每一个大分类的id
                    int id = temshaixuanallList.get(m).getId();
                    StringBuffer sbf = new StringBuffer();
                    sbf.append("\"");
                    sbf.append(id);
                    sbf.append("\":\"");
                    for (int t = 0; t < clickids.size(); t++) {
                        String s = clickids.get(t);
                        String[] split = s.split("=");
                        if (split[1].equals(id+"")){
                            sbf.append(split[0] + ",");
                        }
                    }
                    boolean isadd = false;
                    if (sbf.toString().contains(",")){
                        isadd = true;
                    }
                    String substring = sbf.substring(0, sbf.length() - 1);
                    substring = substring+"\",";
                    if (isadd){
                        paramJson = paramJson+substring;
                    }
                }
                paramJson = paramJson.substring(0,paramJson.length()-1);
                paramJson = paramJson+"}";
                MyLog.e("组合id的json",paramJson+"    JSon格式");


                page = 1;
                if (clickids.size() == 0){
                    paramJson = "";
                }
                getShaixuanResultData(paramJson);

            }
        });

        ll_content.removeAllViews();
        for (int i = 0; i < temshaixuanallList.size(); i++) {
            View view = View.inflate(mcontext, R.layout.item_shaixuanall, null);
            TextView tv_name = view.findViewById(R.id.tv_name);
            //每一模块标题
            tv_name.setText(temshaixuanallList.get(i).getAttr_name());


            List<ShaixuanallBean.DataBean.AttrListBean> attr_list = temshaixuanallList.get(i).getAttr_list();
            final XCFlowLayout flowlayout = view.findViewById(R.id.flowlayout);
            for (int m = 0; m < attr_list.size(); m++) {
                TextView tvview = (TextView) mInflater.inflate(
                        R.layout.item_shuaixuanitem, flowlayout, false);
                tvview.setText(attr_list.get(m).getAttr_value());
                tvview.setTag(attr_list.get(m).getId() + "=" + attr_list.get(m).getKind_id());
                flowlayout.addView(tvview, m);

                for (int k = 0;k<tempClickids.size();k++){
                    String s = tempClickids.get(k);
                    String[] split = s.split("=");
                    String sonid = attr_list.get(m).getId()+"";
                    String fuid = attr_list.get(m).getKind_id()+"";
                    if (sonid.equals(split[0]) && fuid.equals(split[1])){
                        tvview.setBackgroundResource(R.drawable.orange_kong_bg);
                        tvview.setTextColor(getResources().getColor(R.color.colordorange));
                        break;
                    }
                }


                viewssss.add(flowlayout);
                flowlayout.getChildAt(m).setOnClickListener(
                        new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                int childCount = flowlayout.getChildCount();
                                /*for (int n = 0; n < childCount; n++) {
                                    TextView childAt = (TextView) flowlayout.getChildAt(n);
                                    childAt.setBackgroundResource(R.drawable.kong_bg);
                                    childAt.setTextColor(getResources().getColor(R.color.color333));
                                }*/

                                String tab = ((TextView) v).getText()
                                        .toString().trim();
                                String tag = (String) v.getTag();

                                String[] split = tag.split("=");
                                boolean issame = false;
                                //遍历id和父id，判断当前被点击的之前有没有被点击过
                                for (int a = 0; a < tempClickids.size(); a++) {
                                    String s = tempClickids.get(a);
                                    if (s.contains(split[1])) {
                                        //父id一样，都给移除掉
                                        if (s.contains(split[0])){
                                            tempClickids.remove(a);
                                            //说明父id一样，子id一样，就是说是同一个标签
                                            issame = true;
                                        }

                                    }


                                }
                                if (issame){
                                    //如果是同一个，就把当前标签变成没选中状态
                                    v.setBackgroundResource(R.drawable.kong_bg);
                                    ((TextView) v).setTextColor(getResources().getColor(R.color.color333));
                                }

                                if (!issame){
                                    tempClickids.add(tag);
                                    MyLog.e("选中条目", tab + "   选中条目内容     " + tag);
                                    v.setBackgroundResource(R.drawable.orange_kong_bg);
                                    ((TextView) v).setTextColor(getResources().getColor(R.color.colordorange));
                                }
                            }
                        });
            }


            ll_content.addView(view);


        }


        int mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth();
        mPopupWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.FILL_PARENT,
                ActionBar.LayoutParams.FILL_PARENT);
        mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getHeight();
        int mPopupWindowWidth = mPopupWindow.getWidth();
        int mPopupWindowHeight = mPopupWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件

        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int offsetY = DensityUtil.dip2px(mcontext, 24);
            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
                //故而需要在 Android 7.1上再做特殊处理
                int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
                mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
            }
            mPopupWindow.showAtLocation(rl_top, Gravity.NO_GRAVITY, 0, offsetY);
        } else {
//            mPopupWindow.showAsDropDown(rl_top);
            int offsetY = DensityUtil.dip2px(mcontext, 24);
//            if (Build.VERSION.SDK_INT >= 25) { // Android 7.1中，PopupWindow高度为 match_parent 时，会占据整个屏幕
            //故而需要在 Android 7.1上再做特殊处理
            int screenHeight = heightPixels; // 获取屏幕高度
//                int screenHeight = DisplayUtil.getScreenHeight(MainActivity.this); // 获取屏幕高度
            mPopupWindow.setHeight(screenHeight - offsetY); // 重新设置 PopupWindow 的高度
//            }
            mPopupWindow.showAtLocation(rl_top, Gravity.NO_GRAVITY, 0, offsetY);
        }


        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                clickids.clear();
                for (int m = 0;m<tempClickids.size();m++){
                    clickids.add(tempClickids.get(m));
                }
                tempClickids.clear();
                MyLog.e("弹窗消失", "00000000000000");
                tv_caizhi.setTextColor(getResources().getColor(R.color.color333));
                tv_color.setTextColor(getResources().getColor(R.color.color333));
                tv_function.setTextColor(getResources().getColor(R.color.color333));
                tv_area.setTextColor(getResources().getColor(R.color.color333));
                img_caizhi.setImageResource(R.mipmap.icon_down_gray);
                img_color.setImageResource(R.mipmap.icon_down_gray);
                img_function.setImageResource(R.mipmap.icon_down_gray);
                img_area.setImageResource(R.mipmap.icon_down_gray);
            }
        });

    }

    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getActivity().getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }


    /**
     * 筛选目录的内容
     */
    private void getShaixuanData() {
        temshaixuanallList.clear();
        String url = myapp.getWebConfig() + "/api/index/search_condition";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temshaixuanallList = new Gson().fromJson(data.toString(), new TypeToken<List<ShaixuanallBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    private boolean islogin = false;
    /**
     * 筛选结果
     */
    private void getShaixuanResultData(String ids) {
        temgoodsList.clear();
        MyLog.e("请求接口的ids", ids + "   ids");
//        temshaixuanallList.clear();
        String url = myapp.getWebConfig() + "/api/index/product_list";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("search", ids);
        paramsMap.put("page", page + "");
        paramsMap.put("size", size + "");
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temgoodsList = new Gson().fromJson(data.toString(), new TypeToken<List<GoodsBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 3;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 请求头部筛选标题
     */
    private void getTitleData() {
        temSXTabList.clear();
        String url = myapp.getWebConfig() + "/api/index/title_condition";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(mcontext).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temSXTabList = new Gson().fromJson(data.toString(), new TypeToken<List<GoodsShaixuanBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 4;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    goodsRecycleView.setPullLoadMoreCompleted();
                    String str = (String) msg.obj;
                    Toast.makeText(mcontext, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    goodsRecycleView.setPullLoadMoreCompleted();
                    Toast.makeText(mcontext, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
//                    initallbyWindow();

                    break;
                case 3:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (page == 1){
                        goodsRecycleView.scrollToTop();
                        adapter.notifyDataSetChanged();
                    }
                    if (mPopupWindow != null) {
                        mPopupWindow.dismiss();
                    }
                    goodsadapter.setData(temgoodsList);
                    MyLog.e("页码",page+"   页码");
                    if (page == 1) {
                        goodsList.clear();
                    }
                    goodsList.addAll(temgoodsList);
                    adapter.setDatas(goodsList);
                    loadLlay.removeAllViews();
                    goodsRecycleView.setPullLoadMoreCompleted();
                    if (goodsList.size() == 0){
//                        Toast.makeText(mcontext,getString(R.string.nodata),Toast.LENGTH_LONG).show();
                        ll_nodata.setVisibility(View.VISIBLE);
                        goodsRecycleView.setVisibility(View.GONE);
                    }else{
                        ll_nodata.setVisibility(View.GONE);
                        goodsRecycleView.setVisibility(View.VISIBLE);
                    }

                    break;
                case 4:
                    if ("0".equals(apptype)){
                        //木头
                        ll_area.setVisibility(View.VISIBLE);
                        if (temSXTabList.size() > 0) {
                            tv_caizhi.setText(temSXTabList.get(0).getAttr_name());
                            tv_color.setText(temSXTabList.get(1).getAttr_name());
                            tv_function.setText(temSXTabList.get(2).getAttr_name());
                            tv_area.setText(temSXTabList.get(3).getAttr_name());
                            sadapter = new ShaixuanAdapter(mcontext, temSXTabList.get(0).getAttr_list());
                        }
                    }else if ("1".equals(apptype)){
                        //熙然
                        ll_area.setVisibility(View.INVISIBLE);
                        if (temSXTabList.size() > 0) {
                            tv_caizhi.setText(temSXTabList.get(0).getAttr_name());
                            tv_color.setText(temSXTabList.get(1).getAttr_name());
                            tv_function.setText(temSXTabList.get(2).getAttr_name());
//                            tv_area.setText(temSXTabList.get(3).getAttr_name());
                            sadapter = new ShaixuanAdapter(mcontext, temSXTabList.get(0).getAttr_list());
                        }
                    }

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(mcontext, LoginActivity.class);
                        mcontext.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        MyLog.e("商品","onResume");
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        MyLog.e("商品","onHiddenChanged     "+hidden);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
